package resource

import (
	"fmt"
	"time"

	"mallgo/internal/common/response"
	"mallgo/internal/resources/order/api/domain/request"
	"mallgo/internal/resources/order/model"

	"gorm.io/gorm"
)

type OrderResource struct {
	db *gorm.DB
}

func NewOrderResource(db *gorm.DB) *OrderResource {
	return &OrderResource{db: db}
}

// CreateOrder 创建订单
func (r *OrderResource) CreateOrder(req *request.OrderRequest) *response.ResponseObject {

	// 启动事务
	tx := r.db.Begin()

	// 创建订单
	order := model.Order{
		OrderNo:    r.generateOrderNo(),
		CustomerID: &req.UserID,
	}
	if err := tx.Create(&order).Error; err != nil {
		tx.Rollback()
		return response.Error(500, "创建订单失败")
	}

	// 创建订单明细
	for _, item := range req.Items {
		orderItem := model.OrderItem{
			OrderID:         &order.ID,
			ProductID:       &item.ProductID,
			ProductName:     &item.ProductName,
			ProductImageURL: &item.ProductImageURL,
			SkuID:           item.SkuID,
			SkuName:         item.SkuName,
			SkuType:         &item.SkuType,
			Num:             &item.Num,
			Price:           &item.Price,
		}
		if err := tx.Create(&orderItem).Error; err != nil {
			tx.Rollback()
			return response.Error(500, "创建订单明细失败")
		}
	}

	tx.Commit()
	return response.Success(order)
}

// GetOrder 查询订单
func (r *OrderResource) GetOrder(orderID int64) *response.ResponseObject {
	var order model.Order
	if err := r.db.Preload("OrderItems").First(&order, orderID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return response.Error(404, "订单未找到")
		}
		return response.Error(500, "查询订单失败")
	}
	return response.Success(order)
}

// DeleteOrder 删除订单
func (r *OrderResource) DeleteOrder(orderID int64) *response.ResponseObject {
	tx := r.db.Begin()

	// 删除订单明细
	if err := tx.Where("order_id = ?", orderID).Delete(&model.OrderItem{}).Error; err != nil {
		tx.Rollback()
		return response.Error(500, "删除订单明细失败")
	}

	// 删除订单
	if err := tx.Delete(&model.Order{}, orderID).Error; err != nil {
		tx.Rollback()
		return response.Error(500, "删除订单失败")
	}

	tx.Commit()
	return response.Success(nil)
}

// generateOrderNo 生成订单号
func (r *OrderResource) generateOrderNo() string {
	timestamp := time.Now().Format("20060102150405")
	random := fmt.Sprintf("%04d", time.Now().Nanosecond()%10000)
	return fmt.Sprintf("%s%s", timestamp, random)
}
